package com.ai.emall.business.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ai.emall.bean.gbean.SysOp;
import com.ai.emall.bean.gbean.SysOpExample;
import com.ai.emall.business.interfaces.IPmLoginAuthSV;
import com.ai.emall.constants.EmallBusiConstants;
import com.ai.emall.constants.EmallExceptCodeConstants;
import com.ai.emall.dao.gdao.SysOpMapper;
import com.ai.emall.utils.exception.BusinessException;
import com.ai.emall.utils.util.CollectionUtil;
import com.ai.emall.utils.util.DateUtil;
import com.ai.emall.utils.util.MD5Util;

/** 
 * 
 * @author zhaowg3
 * @Date 2017年1月6日
 */
@Service
public class PmLoginAuthSVImpl implements IPmLoginAuthSV{
	@Autowired
	private SysOpMapper sysOpMapper;
	@Override
	public SysOp login(String userName, String pwd, String token) throws Exception {
		SysOpExample opExample = new SysOpExample();
		SysOpExample.Criteria sql = opExample.createCriteria();
		sql.andLoginNameEqualTo(userName);
		sql.andDataStateEqualTo(EmallBusiConstants.SysOp.DataStatus.NORMAL);
		List<SysOp> sysOps = sysOpMapper.selectByExample(opExample);
		if(CollectionUtil.isEmpty(sysOps))
			throw new BusinessException(EmallExceptCodeConstants.Login.USERNAME_NOT_EXISTS, "用户不存在");
		SysOp op = sysOps.get(0);
		//对数据库中密码进行二次加密
		String key = MD5Util.MD5(op.getLoginPswd()+token);
		if(!key.equals(pwd))
			throw new BusinessException(EmallExceptCodeConstants.Login.PWD_ERROR, "密码不正确");
		return op;
	}

	@Override
	public void modifyPwd(String userName,String oldPwd, String newPwd, String token,Long opId) throws Exception {
		//判断旧密码是否正确
		SysOp op = login(userName,oldPwd,token);
		//修改密码
		op.setLoginPswd(newPwd);
		op.setModifyOpid(opId);
		op.setModifyTime(DateUtil.getSysDate());
		sysOpMapper.updateByPrimaryKeySelective(op);
	}

}
